﻿<html>
<head>
<title>Receiver</title>
<style>
.video_class{
	width:70%;
	height:70%;
	background: #000;
}
#stop_live_by_examiner{
	 display:none;
}
#set_buffertime_section{
	position:absolute;
	right:20%;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jquery.color-2.1.2.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="js/swiper.js"></script>


    <script type="text/javascript" src="myjs/ajaxutils.js"></script>
    <script type="text/javascript" src="myjs/base.js"></script>


    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/bootstrap-reboot.css"/>
    <link rel="stylesheet" href="css/bootstrap-grid.css"/>
    <link rel="stylesheet" href="css/swiper.css">
    <link rel="stylesheet" href="mycss/base.css">
	<link rel="stylesheet" href="mycss/userinfo.css">

</head>
<body>
<nav id="nav_bar" class="navbar navbar-expand-md bg-dark navbar-dark justify-content-center align-items-center">
    <!-- Brand -->
    <div class="d-flex  justify-content-center align-items-center flex-wrap" style="width: 95rem;margin: 0 auto">
        <a class="navbar-brand my-auto" href="#" style="font-size: 1.8rem;font-weight: bold">
            <!--            <img src="https://edu-image.nosdn.127.net/C0124E0336721FF65563B76A16A8143F.png?imageView&thumbnail=190y28&quality=100"-->
            <!--                 alt="Logo">-->
            <span class="glyphicon glyphicon-book" style="color: lawngreen"></span> Elearning
        </a>

        <!-- Toggler/collapsibe Button -->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!-- Navbar links -->
        <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a href="Home.html" class="nav-link">首页</a>
                </li>
                <li class="nav-item">
                    <a href="CourseList.html" class="nav-link">所有课程</a>
                </li>
                <li class="nav-item">
                    <a href="userinfo.html#/user/courses_info" class="nav-link">我的课程</a>
                </li>
                <li class="nav-item">
                    <a href="LiveList.html" class="nav-link">浏览直播</a>
                </li>
            </ul>

            <div id="search_bar" class="form-inline d-flex justify-content-center sm-hide">
                <form class="form-inline" action="Search.html" method="post" target="_top" name="nav-form"
                      onsubmit="setSearchKey()" style="margin-bottom: 0px;">
                    <input class="form-control" type="search" placeholder="搜索感兴趣的课程" required name="search-box">
                    <button class="btn btn-success" type="submit"><i class="fa fa-search" aria-hidden="true">搜索</i>
                    </button>
                </form>
                <!--                <input class="form-control " type="text" placeholder="搜索课程"/>-->
                <!--                <button class="btn btn-primary" type="submit">搜索</button>-->
            </div>
            <div id="head_div"
                 class="text-center d-flex justify-content-center align-items-center position-relative sm-hide mx-auto"
                 style="height: 45px;width: 130px;">
                <div id="alarm_ico_div">
                    <a id="alarm_ico" href="Message.html" class="p-1 m-2" style="font-size: 25px;position: relative">
                        <span id="alarm_ico_word" class="glyphicon glyphicon-bell"></span>
                        <span id="alarm_ico_count" style="color: white;text-decoration: none;display: none">0</span>
                    </a>
                </div>
                <img class="user_head_img" id="user_head"
                     style="width: 44px;height: 44px;border: 2px solid #343a40;cursor: pointer" alt="头像">
                <!--用户菜单悬浮框-->
                <div id="user_flex" class="card m-0" style="overflow: hidden;right: 0;top: 100%">
                    <div class="card-body d-flex justify-content-center flex-wrap">
                        <div id="user_head_name" class="d-flex">
                            <img class="user_head_img" alt="头像"/>
                            <div class="ml-4">
                                <h4 class="user_name_all" id="flex_user_name" style="font-size: 1.5rem"></h4>
                                <span style="font-size: 13px;color: #6c757d">手机号:</span><span class="user_phone_all"
                                                                                              id="flex_user_phone"
                                                                                              style="font-size: 13px;color: #6c757d"></span>
                            </div>
                        </div>
                        <div id="user_flex_btn_div" class="p-1 mt-2 d-flex flex-wrap justify-content-around">
                            <a href="userinfo.html#/user/courses_info" class="user_flex_btn">
                                <span class="glyphicon glyphicon-book"></span>
                                <span>&ensp;我的课程</span>
                            </a>
                            <a href="userinfo.html#/user/order_info" class="user_flex_btn">
                                <span class="glyphicon glyphicon-list-alt"></span>
                                <span>&ensp;订单管理</span>
                            </a>
                            <a href="userinfo.html#/user/courses_published" class="user_flex_btn mt-2">
                                <span class="glyphicon glyphicon-upload"></span>
                                <span>&ensp;发布课程</span>
                            </a>
                            <a href="userinfo.html#/user/user_info" class="user_flex_btn mt-2">
                                <span class="glyphicon glyphicon-cog "></span>
                                <span>&ensp;个人设置</span>
                            </a>
                        </div>
                        <button id="open_live_btn" type="button" class="btn btn-primary mx-auto mt-1"
                                style="border-radius: 100px;">开启直播
                        </button>
                        <button onclick="logout()" type="button" class="btn btn-danger mx-auto mt-1"
                                style="border-radius: 100px;">注销登录
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</nav>
	<div id="back_img_div" class="d-flex" style="min-width: 95rem">
    <div id="user_short_info_div" class="d-flex align-items-center">
        <div class="p-2 ml-4">
            <img class="user_head_img" id="user_big_head_img">
        </div>
        <div id="user_short_info" class="ml-3">
            <h1 class="user_name user_name_all" id="show_live_name"></h1>
            <p>
                <!--<span id='show_live_name'>默认直播间标题</span>
                -->
				<span>讲师：<span id='show_live_teacher_name' class="user_phone_all"></span>  当前观看人数 <span id='watcher_number' class="user_phone_all">0</span> 人</span>
            </p>
            <p>直播描述：<span id='show_live_info' class="user_description_all">啥也没有</span></p>
			<!--<p>当前观看人数 <span id='watcher_number'>0</span> 人</p>-->
        </div>
    </div>
</div>
	<!--
	<p id='show_live_name'>默认直播间标题</p><br>
	<h3 id='show_live_info'>直播间描述</h3>
	-->
	

	<button id='stop_live_by_examiner'>封禁</button>
	
	<center>
	<br>
    <video id="RemoteVideo" class='video_class' autoplay controls></video>
	<br>
	</center>
	<div id='set_buffertime_section'>
		<select id='buffered_time'>
			<option value="N/A" selected="selected">N / A</option>
			<option value="20m">20 m</option>
			<option value="5m">5 m</option>
			<option value="5s">5 s</option>
		</select>
	<a title="您可以自行选择浏览器为您缓存多久的视频
更短的缓存时间有助于减轻您浏览器的负担
更长的缓存时间可以让您回看更早之前的直播内容"
	>[缓存时间?]</a>
	</div>
	<!--
	<a>input the liver you want to watch</a>
	<br>
	<input id='liver_wanted' type='text'></input>
	<br>
	<a>input your username</a>
	<br>
	<input id='watcher_wanted' type='text'></input>
	<button id='get_liver_wanted'>connect</button>-->
	<br>
	
	<br>
	
    
	<script>
		var liver_wanted = null;//想要观看的liver
		var watcher_wanted = null;//观看直播的user
		var mediastream = null;
		var str_liveId_and_token,str_liveId,str_token;
		var user_token = null;
		
		//获得的就是当前的?liveId=xx?t=AAA 切分字符串来获得id
		console.log(window.location.search);
		try{
			str_liveId_and_token = window.location.search.split("?");
			str_liveId = str_liveId_and_token[1];
			str_token = str_liveId_and_token[2];
			liver_wanted = str_liveId.split("=")[1];
			user_token = str_token.split("=")[1];
			console.log(liver_wanted+"/"+user_token);
		}catch(e){
			console.log('test page');
		}
	
		var buffered_time_limit = 999999;//单位是秒
		//下拉菜单选择缓冲时间
		$('#buffered_time').change(function(event){
			var selected_value = event.target.options[event.target.options.selectedIndex].value;
			switch(selected_value){
				case "N/A":
					buffered_time_limit = 999999;
					break;
				case "20m":
					buffered_time_limit = 1200;
					break;
				case "5m":
					buffered_time_limit = 300;
					break;
				case "5s":
					buffered_time_limit = 5;
					break;
			}
			//alert('select = '+ buffered_time_limit);
		});
	
	
		var RemoteVideo = document.getElementById('RemoteVideo');
		RemoteVideo.addEventListener('error',function(error){
			console.log(error);
		});
		
		
		//创建MediaSource
		var mediasource = new MediaSource;
		var sourcebuffer;
		
        // 与信令服务器的WebSocket连接
        //var socket = new WebSocket("ws://127.0.0.1:3000");
		var socket = new WebSocket("ws://182.92.1.116:3000");

        // stun和turn服务器
		
		var iceServer = { iceServers: [
						{
							urls:"stun:stun.l.google.com:19302"
						},
						{
                        urls: "turn:106.52.27.49:3478",
						username:"winka",
						credential:"9587"
                      }]
		};
		//检查浏览器支持的编码格式
		var types = ['video/webm', 
             'audio/webm', 
             'video/webm\;codecs=vp8', 
			 'video/webm\;codecs=vp9', 
             'video/webm\;codecs=daala', 
             'video/webm\;codecs=h264', 
             'audio/webm\;codecs=opus', 
			 'video/webm; codecs=what',
			 'video/webm; codecs=opus,vp9',
             "video/mpeg"];

		for (var i in types) { 
			console.log( "Type " + types[i] + " is" + (MediaRecorder.isTypeSupported(types[i]) ? " support " : " not support")); 
		}

		mediasource.addEventListener('error',function(e){
			console.log('error at mediasource:'+e);
		});
	  
		//将MediaSource附加到媒体元素
		RemoteVideo.src = URL.createObjectURL(mediasource);
	  
		//添加媒体附着事件
		mediasource.addEventListener('sourceopen',function(e){
			//创建sourcebuffer
			//sourcebuffer = mediasource.addSourceBuffer('video/webm; codecs=opus,vp9');
			sourcebuffer = mediasource.addSourceBuffer('video/webm; codecs=opus,vp8');
			//修改模式 Important!!!! 不然需要添加时间戳
			sourcebuffer.mode = 'sequence';
			//添加错误监听
			sourcebuffer.onerror = function(error){
				console.log('======sourcebuffer error occured :');
				console.log(error);
			}
		});
		
		function getUserIdByLiveId(liveId,power_str){
			var request_list = {
				"liveId":liver_wanted
			};
			let data_tosend = JSON.stringify(request_list);
			$.ajax({
				type : "POST",
				contentType: "application/json;charset=UTF-8",
				url : "http://120.55.165.31:8080/Elearning/api/liveServer/live/selectLiveByLiveId",
				data : data_tosend,
				success : function(result) {
					//从result中取得liveId，作为直播发起者的标识发送给服务器
					console.log(result);
					var user_id;
					switch(result.status){
						case 200:
							user_id = result.data.userId;
							console.log('getUserIdByLiveId:'+result.data.userId);
							//封禁该用户
							console.log('user_id:'+user_id);
							var request_list = {
								"userId":user_id,
								"forbidUserReason":"直播内容违规",
								"forbidUserType":power_str,
								"token":user_token
							};
			
							let data_tosend = JSON.stringify(request_list);
							data_tosend = data_tosend.replace('"token":','"token": ');
							$.ajax({
								type : "POST",
								contentType: "application/json;charset=UTF-8",
								url : "http://120.55.165.31:8080/Elearning/api/examiner/forbidUser/addForbidUser",
								data : data_tosend,
								success : function(result) {
									//从result中取得liveId，作为直播发起者的标识发送给服务器
									console.log(result);
									switch(result.status){
										case 200:
											alert('已封禁该用户');
											break;
										default:
											alert('无法封禁:'+result.status);
											break;
									}
								},
            				//请求失败，包含具体的错误信息
								error : function(e){
									console.log(e.status);
									console.log(e.responseText);
								}
							});
							break;
						default:
							console.log('error at getUserIdByLiveId');
							return 'FailToGetUserId';
							break;
					}
					
				},
            //请求失败，包含具体的错误信息
				error : function(e){
					console.log(e.status);
					console.log(e.responseText);
				}
			});
			
		}
		//窗口加载完成后执行
		window.onload = getUserInfoByLiveId(liver_wanted);
		
		function getUserInfoByLiveId(liveid_param){
			var request_list = {
				"liveId":parseInt(liveid_param)
			};		
			let data_tosend = JSON.stringify(request_list);
			data_tosend = data_tosend.replace('"token":','"token": ');
			$.ajax({
				type : "POST",
				contentType: "application/json;charset=UTF-8",
				url : "http://120.55.165.31:8080/Elearning/api/liveServer/live/selectLiveByLiveId",
				data : data_tosend,
				success : function(result) {
					//从result中取得liveId，作为直播发起者的标识发送给服务器
					console.log(result);
					switch(result.status){
						case 200:
							alert('已经获得直播信息');
							console.log('已经获得直播信息');
							console.log(result.data);
							
							$('#show_live_teacher_name').text(result.data.teacherName);
							//要获得讲师头像，需要用userId去获得头像
							GetAndSetUserImageByUserId(result.data.userId);
							break;
						default:
							alert('无法获得直播信息:'+result.status);
							break;
					}
				},
            	//请求失败，包含具体的错误信息
				error : function(e){
					console.log(e.status);
					console.log(e.responseText);
				}
			});
		}
		
		function GetAndSetUserImageByUserId(userId_param){
			var request_list = {
				"userId":userId_param
			};		
			let data_tosend = JSON.stringify(request_list);
			data_tosend = data_tosend.replace('"token":','"token": ');
			$.ajax({
				type : "POST",
				contentType: "application/json;charset=UTF-8",
				url : "http://120.55.165.31:8080/Elearning/api/all/user/selectUserByUserId",
				data : data_tosend,
				success : function(result) {
					//从result中取得liveId，作为直播发起者的标识发送给服务器
					console.log(result);
					switch(result.status){
						case 200:
							console.log('get userImage');
							$('#user_big_head_img').attr("src","http://120.55.165.31:8080/Elearning/" + result.data.userImage);
							break;
						default:
							alert('无法获得直播信息:'+result.status);
							break;
					}
				},
            	//请求失败，包含具体的错误信息
				error : function(e){
					console.log(e.status);
					console.log(e.responseText);
				}
			});
		
		}
		
		//向直播服务器发送关闭直播申请
		//向DB发送封禁
		//参数为发送给服务器的data.power
		function stop_and_prohibit_this_live(power_str){
			//ws向服务器发送关闭直播
			alert('封禁直播');
			socket.send(JSON.stringify({
                    "event": "_closelive"
                }));
				
			
			//向DB发送封禁
			//通过liveId获取用户id
			getUserIdByLiveId(liver_wanted,power_str);
			
		}
		//向DB检查当前用户是否为审核员
		function check_if_examiner(){
			var request_list = {
				"token": user_token
			};
			let data_tosend = JSON.stringify(request_list);
			data_tosend = data_tosend.replace('"token":','"token": ');
			$.ajax({
				type : "POST",
				contentType: "application/json;charset=UTF-8",
				url : "http://120.55.165.31:8080/Elearning/api/user/user/getUserCurrent",
				data : data_tosend,
				success : function(result) {
					//从result中取得liveId，作为直播发起者的标识发送给服务器
					console.log(result);
					switch(result.status){
						case 200:
							var paseredJSON = $.parseJSON(result.data.power);
							console.log(paseredJSON);
							if(paseredJSON.allExaminer == 'allow'){
								console.log('is a examiner');
								$('#stop_live_by_examiner').css('display','block');
								$('#stop_live_by_examiner').click(function(){
									//封禁直播功能
									paseredJSON.teacherAddLive = "forbid_2";
									var newJSON_str = JSON.stringify(paseredJSON);
									console.log('修改后的Power：'+newJSON_str);
									stop_and_prohibit_this_live(newJSON_str);
								});
							}else{
								console.log('not a examiner');
							}
							break;
						default:
							console('error at check_if_examiner status : '+result.status);
							break;
					}
				},
            //请求失败，包含具体的错误信息
				error : function(e){
					console.log(e.status);
					console.log(e.responseText);
				}
			});
			
			
			//if()
			//如果是审核员，将封禁按钮显示，并且添加封禁按钮监听
			
		}

		
        // 创建PeerConnection实例 (参数为null则没有iceserver，即使没有stunserver和turnserver，仍可在局域网下通讯)
        var pc = new RTCPeerConnection(iceServer);
		var datachaneel = null;
		var reader = new FileReader();
		//对方pc创建数据通道
		pc.ondatachannel = function(event){
			datachaneel = event.channel;
			console.log(datachaneel);
			//收到消息
			datachaneel.binaryType = "arraybuffer";
			datachaneel.onmessage = dc_receive_message;
			datachaneel.onopen = dc_statechange;
			datachaneel.onclose = dc_statechange;
		}
		//LiveArr.push(live);
	

		//当前正在接收的file的总size
		var now_file_size = null;
		//已经收到的size
		var now_received_size = 0;
		//用于拼接成blob
		var arr = [];
		//DataChannel收到消息
		function dc_receive_message(event){
//			console.log(event);
			if(typeof(event.data)=='string'){
				//重置
				now_file_size = null;
				now_received_size = 0;
				arr = [];
				
				var obj = eval ("(" + event.data + ")");
				console.log('get file size : '+obj.filesize);
				now_file_size = obj.filesize;
				
				
			}else{
				if(now_file_size != null){
					arr.push(event.data);

					//更新接收到的size
					//blob是size，arraybuffer是byteSize
					now_received_size += event.data.byteLength;
					//显示接收进度
//					console.log('Now : '+now_received_size+"/"+now_file_size);
					
					
					if(now_received_size==now_file_size){
						//测试直接由blob播放
						var blob = new Blob(arr,{'type':'video/webm; codecs=opus,vp8'});

						//将总的播放
						reader.onloadend = function(e){
							sourcebuffer.appendBuffer(reader.result);
						}
						reader.readAsArrayBuffer(blob);

						//组装完成后清空记录
						now_file_size = null;
						now_received_size = 0;
						arr = [];

						
						//console.log(RemoteVideo);
						sourcebuffer.addEventListener('updateend',function(event){
							if(!sourcebuffer.updating){
								//设置持续时间
								try{
									mediasource.duration = 5;//初始加载5s
									console.log('set duration time :' + mediasource.duration);
								}catch(e){
									//console.log(e);
								}
							}
						});
						
						if (RemoteVideo.buffered.length && RemoteVideo.buffered.end(RemoteVideo.buffered.length-1) - RemoteVideo.buffered.start(0) > buffered_time_limit){
							console.log('clear buffer from 0 to '+ (RemoteVideo.buffered.end(RemoteVideo.buffered.length-1) - buffered_time_limit));
							//sourcebuffer.remove(0, RemoteVideo.buffered.end(RemoteVideo.buffered.length - 1) - buffered_time_limit);
							sourcebuffer.remove(0, RemoteVideo.buffered.end(RemoteVideo.buffered.length-1) - buffered_time_limit);
							
						}
					}
					
				}
			}
		
		

			
		}
		//DataChannel的状态改变
		function dc_statechange(event){
			console.log(event);		
		}
		
        // 发送ICE候选到其他客户端
        pc.onicecandidate = function(event){
            if (event.candidate !== null) {
				//找到ice候选后socket发送
                socket.send(JSON.stringify({
                    "event": "_ice_candidate",
                    "candidate": event.candidate
                    
                }));
            }
        };

		console.log(pc);
		//当服务器挂载媒体流触发
		/*
		pc.ontrack = function(event){
			console.log('get MediaStream by ontrack! ');
			console.log(event);
			var RemoteVideo = document.getElementById('RemoteVideo');
			//可能会出错
			//var mediastream = new MediaStream();
			//mediastream.addTrack(event.track);
			mediastream = event.streams[0];

			RemoteVideo.src = window.URL && window.URL.createObjectURL(mediastream) || mediastream
			//RemoteVideo.srcObject = mediastream;
		
		}
		pc.onaddstream = function(event){
			console.log('get MediaStream by onaddstream! ');
			console.log(event);
			var RemoteVideo = document.getElementById('RemoteVideo');

			var mediastream = event.stream;
			
			console.log(mediastream.getAudioTracks());
			console.log(mediastream.getVideoTracks());
			//RemoteVideo.srcObject = mediastream;
			RemoteVideo.src = window.URL && window.URL.createObjectURL(mediastream) || mediastream
		
		}
		pc.onremovestream = function(event){
			console.log('MediaStream Remove ');
			console.log(event);
		
		}*/
		/*
        // 发送offer和answer的函数，发送本地session描述
        var sendOfferFn = function(desc){
			console.log('send offer');
			console.log(desc);
            pc.setLocalDescription(desc);
            socket.send(JSON.stringify({ 
                "event": "_offer",
                "data": {
                    "sdp": desc
                }
            }));
			
			console.log('send who I am after send offer');
			socket.send(JSON.stringify({
                   "event": "_who",
					"data": "receiver",
					"liver": liver,
					"watcher": "user2"
			}));
			
        };
		*/
		//收到offer后返回answer
        var sendAnswerFn = function(desc){
			console.log('send Answer');
            pc.setLocalDescription(desc);
            socket.send(JSON.stringify({ 
                "event": "_answer",
                "data":  desc
                
            }));
        };

/*
		//暂时不主动发送，由服务器端来进行发送试试
		console.log('send offer');
        pc.createOffer(sendOfferFn, function (error) {
			console.log('Failure callback: ' + error);
            });
*/	
		
		//处理到来的信令
        socket.onmessage = function(event){
			//console.log('get msg');
            var json = JSON.parse(event.data);
  //          console.log('onmessage: ', json);
            //如果是一个ICE的候选，则将其加入到PeerConnection中，否则设定对方的session描述为传递过来的描述
            if( json.event === "_ice_candidate" ){
                pc.addIceCandidate(new RTCIceCandidate(json.candidate));
            }else if(json.event === "_watcher_number"){
				//console.log('watcher_number : '+json.watcher_number);
				$('#watcher_number').text(json.watcher_number);
			
			} else if(json.event === "_offer") {
					console.log('receive offer set RemoteDescription');

					//显示直播间名称
					$('#show_live_name').text(json.live_name);
					$('#show_live_info').text(json.live_info);
                    //pc.createAnswer(sendAnswerFn, function (error) {
                    //    console.log('Failure callback: ' + error);
                    //});
					pc.setRemoteDescription(new RTCSessionDescription(json.data)).then(function(){
						// 如果是一个offer，那么需要回复一个answer
						return pc.createAnswer();
					}).then(function(answer) {
						console.log('create and send answer');
						pc.setLocalDescription(answer);
						return answer;
					}).then(function(answer){
						//将Answer发送回客户端
						socket.send(JSON.stringify({ 
							"event": "_answer",
							"data": answer	
						}));
					})
					.catch(function (error) {
						console.log('Failure callback at handle _offer: ' + error);
					});
					
					start_heartcheck(socket);//启动心跳
            }
            
        };
		
		//监听websocket，当成功连接时，发送
		//在正式版本中，应该在连接建立后向服务器发送_who告知服务器自己是观看方，服务器接收到之后向该发起offer
		socket.addEventListener('open', function () {
			//一个更新的createoffer，包含具体的发送
			/*
			pc.createOffer().then(function(offer) {
				pc.setLocalDescription(offer);
				return offer;
			})
			.then(function(offer) {
				socket.send(JSON.stringify({ 
					"event": "_offer",
					"data": {
						"sdp": offer
						}
				}));
				
				//正式版本中应该在这里发送，因为是从链接中截取 //测试版本由connect按钮来发送
				/*
				console.log('send who I am after send offer');
				socket.send(JSON.stringify({
                   "event": "_who",
					"data": "receiver",
					//"liver": liver_wanted,
					"liver": "1",
					"watcher": liver_watch
				}));
				*/
				/*
			})
			.catch(function(reason) {
				// An error occurred, so handle the failure to connect
				console.log('error in createoffer : '+reason);
			});
			*/
			console.log('ws open');
			//自动观看直播
			start_watch_live();
			//检查是否是审核员
			check_if_examiner();
		});
		
		//开始观看直播
		function start_watch_live(){
			//liver_wanted = document.getElementById('liver_wanted').value;
			//watcher_wanted = document.getElementById('watcher_wanted').value;
			console.log('connecting to live '+liver_wanted);
			socket.send(JSON.stringify({
                   "event": "_who",
					"data": "receiver",
					"liver": liver_wanted,
					"watcher": null
					//"watcher":watcher_wanted
				}));
		}
		//var get_liver_wanted = document.getElementById('get_liver_wanted');
		//get_liver_wanted.addEventListener('click',start_watch_live);
		
        
		//循环显示当前ws状态
		function now_ice_state(){
			console.log('now ice connection state: ' + pc.iceConnectionState);
			console.log('now ice gathering state: ' + pc.iceGatheringState);
			console.log(pc);
			setTimeout(now_ice_state,1000);
		}
		//setTimeout(now_ice_state,1000);
		
		const heartbeat_time = 10000;
		//发送心跳的websocket与每隔多久发送一次
		function start_heartcheck(ws){
			setTimeout(send_heartcheck,heartbeat_time);
		}
		//发送
		function send_heartcheck(ws){
			console.log('heartbeat');
			socket.send(JSON.stringify({
				"event": "_heartcheck",
				"data": "pong"
			}));
			setTimeout(send_heartcheck,heartbeat_time);
		}
		
		
    </script>
</body>
</html>